import MethodsJS from '../methods.js';

// 计算摄像头角度 - 北云台
export const jisuanjiaoduBei = () => {
  const bei = {
    lon: 119.45206246145788,
    lat: 29.17467466774048,
    angle: 18 + 5,
  };
  const leftPoint = {
    lon: 119.45316323332261,
    lat: 29.177701801464167,
    distance: 353,
    x: 0.7482,
    y: -0.0365,
    angle: 3.5662292993502547,
    ver: 13.27,
  };
  const rightPoint = {
    lon: 119.4536253794058,
    lat: 29.17727788347233,
    distance: 329,
    x: 0.7792,
    y: -0.0381,
    angle: 3.8256333936479905,
    ver: 13.69,
  };
  const treePoint = {
    lon: 119.45549859001903,
    lat: 29.186789991411942,
    distance: 1392.67,
    x: 0.7382,
    y: -0.0288,
    angle: 0.9069596786192164,
  };
  const lx = MethodsJS.calculatePanAngle(bei.lon, bei.lat, leftPoint.lon, leftPoint.lat);
  const rx = MethodsJS.calculatePanAngle(bei.lon, bei.lat, rightPoint.lon, rightPoint.lat);
  const tx = MethodsJS.calculatePanAngle(bei.lon, bei.lat, treePoint.lon, treePoint.lat);
  const offsetx = 252.5;
  console.log('lx: ', (lx + offsetx) / 360);
  console.log('rx: ', (rx + offsetx) / 360);
  console.log('tx: ', (tx + offsetx) / 360);
  const ly = MethodsJS.calculateTiltAngle(leftPoint.distance, 22);
  const ry = MethodsJS.calculateTiltAngle(rightPoint.distance, 22);
  const ty = MethodsJS.calculateTiltAngle(treePoint.distance, 22);
  const offsetY = 9;
  console.log('******************************');
  console.log('offsetY: ', offsetY);
  console.log('******************************');
  console.log('ly: ', -(ly + offsetY) / 360);
  console.log('ry: ', -(ry + offsetY) / 360);
  console.log('ty: ', -(ty + offsetY) / 360);
}
export const jisuanjiaoduNan = () => {
  const nan = {
    lon: 119.45208554818058,
    lat: 29.17450635050248,
    angle: 18 + 5,
  };
  const leftPoint = {
    lon: 119.44857296662657,
    lat: 29.168936520072066,
    distance: 709,
    x: 0.7482,
    y: -0.0365,
    angle: 3.5662292993502547,
    ver: 13.27,
  };
  const lx = MethodsJS.calculatePanAngle(nan.lon, nan.lat, leftPoint.lon, leftPoint.lat);
  const offsetx = 71.3;
  console.log('lx: ', (lx + offsetx) / 360);
  const ly = MethodsJS.calculateTiltAngle(leftPoint.distance, 22);
  const offsetY = 12.5;
  console.log('******************************');
  console.log('offsetY: ', offsetY);
  console.log('******************************');
  console.log('ly: ', -(ly + offsetY) / 360);
}

// 计算摄像头角度 - 海康
export const jisuanjiaodu2 = () => {
  const bei = {
    lon: 119.45266913683801,
    lat: 29.174505831277514,
  };
  const nan = {
    lon: 119.4514491986614,
    lat: 29.174752183369726,
  };
  const pointBei = {
    lon: 119.45348,
    lat: 29.177786666666666,
    distance: 530,
    x: 0,
    y: 0,
    angle: 0,
    ver: 17.74,
    z: 0.12,
  };
  const pointNan = {
    lon: 119.44916314302625,
    lat: 29.17042715017223,
    distance: 530,
    x: 0,
    y: 0,
    angle: 0,
    ver: 17.74,
    z: 0.12,
  };
  const point3 = {
    lon: 119.44913803199024,
    lat: 29.17041501153308,
    distance: 534,
    x: 0,
    y: 0,
    angle: 0,
    ver: 0,
    z: 0.22,
  }
  const x1 = MethodsJS.calculatePanAngle(nan.lon, nan.lat, point3.lon, point3.lat);
  const offsetxBei = 142;
  const offsetxNan = -17.9;
  console.log("x1: ", x1)
  let angle = x1 + offsetxNan;
  if (angle > 180) {
    angle -= 360
  }
  const x = angle / 180
  console.log('x: ', x);
  const y1 = MethodsJS.calculateTiltAngle(point3.distance, 13.75);
  console.log("y1: ", y1)
  const y = 1 + (y1 - -20) * -2 / 110
  console.log('y: ', y);
  console.log("*************************")
  console.log(`x=${x}&y=${y}&z=0.02`)
  console.log("*************************")
}

// 从日志中提取数据
// import { text } from "./AIS01090908/log.js"
const text = {}
export function extractRadarAndClassBData() {
  // 匹配雷达数据，捕获前面的时间戳和数据内容
  const radarRegex = /(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})收到雷达原始数据：({.*?})/g;
  // 匹配 ClassB 数据
  const classBRegex = /收到ClassB数据：({.*?})/g;

  let radarData = [];
  let classBData = [];

  // 提取雷达数据
  let radarMatch;
  while ((radarMatch = radarRegex.exec(text)) !== null) {
    const radarJSON = JSON.parse(radarMatch[2]); // 解析 JSON 数据
    radarJSON.dataTime = radarMatch[1]; // 添加时间字段
    radarJSON.realId = (radarJSON.secret || 125) + '' + radarJSON.id;
    radarData.push(radarJSON);
  }

  // 提取 ClassB 数据
  let classBMatch;
  while ((classBMatch = classBRegex.exec(text)) !== null) {
    classBData.push(JSON.parse(classBMatch[1]));
  }

  return {
    radarData,
    classBData
  };
}
export function extractRadarBData() {
  // 匹配雷达数据，捕获前面的时间戳和数据内容
  const radarRegex = /(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})收到雷达原始数据：({.*?}})/g;

  let radarData = [];
  let classBData = [];

  // 提取雷达数据
  let radarMatch;
  while ((radarMatch = radarRegex.exec(text)) !== null) {
    console.log("radarMatch: ", radarMatch)
    const radarJSON = JSON.parse(radarMatch[2]); // 解析 JSON 数据
    console.log("radarJSON: ", radarJSON)
    // 提取每个对象的值，去掉数字键
    const radarValues = Object.values(radarJSON);

    // 对每个值对象添加时间和 realId 字段
    radarValues.forEach(item => {
      item.dataTime = radarMatch[1]; // 添加时间字段
      item.realId = (item.secret || 126) + '' + item.id; // 添加 realId 字段
      radarData.push(item); // 将每个雷达数据对象推入 radarData
    });
  }

  return {
    radarData,
    classBData
  };
}

// 计算雷达数据的时间是否连贯
export function leidatime(radarData) {
  let obj = {};
  for (let key in radarData) {
    obj[key] = []
    const data = radarData[key];
    let currentTime = ""
    for (let item of data) {
      if (!currentTime) {
        currentTime = item.dataTime;
        console.log("currentTime: ", currentTime)
      } else {
        const number = +new Date(item.dataTime) - +new Date(currentTime)
        if (number > 1000) {
          obj[key].push([item.dataTime, (number / 1000).toFixed(0)])
        }
        currentTime = item.dataTime;
      }
    }
  }
  for (let key in obj) {
    if (obj[key].length == 0) {
      delete obj[key]
    }
  }
  return obj
}

// 分离AIS
export function fenliAIS(data, prop = 'mmsi') {
  let list = {};
  for (let item of data) {
    if (!list[item[prop]]) {
      list[item[prop]] = [item];
    } else {
      list[item[prop]].push(item);
    }
  }
  return list
}
// 分离雷达
export function fenliLeida(data, prop = 'mmsi') {
  let list = {};
  for (let item of data) {
    // if (item.secret === "126") {
    if (!list[item[prop]]) {
      list[item[prop]] = [item];
    } else {
      list[item[prop]].push(item);
    }
    // }
  }
  return list
}

// 去除相同的时间
export function deleteRadarByTime(data) {
  let time = "";
  let list = []
  for (let item of data) {
    if (item.dataTime !== time) {
      list.push(item)
      time = item.dataTime
    }
  }
  return list;
}

// 判断融合数据中融合次数
// import rongheshuju from "./AIS01090908/ronghe.json"
const rongheshuju = {}
export function rongheNumber() {
  let obj = {};
  for (let key in rongheshuju) {
    const list = rongheshuju[key];
    obj[key] = []
    for (let index = 0; index < list.length; ++index) {
      const item = list[index]
      const length = obj[key].length;
      if (item.dataType === "3") {
        if (item.navStatus.startsWith("125")) {
          if (length === 0) {
            const aisData = { radar: item.navStatus, number: 1 };
            obj[key].push(aisData)
          } else {
            if (!obj[key][length - 1].radar) {
              const aisData = { radar: item.navStatus, number: 1 };
              obj[key].push(aisData);
            } else {
              obj[key][length - 1].number += 1;
            }
          }
        } else {
          break
        }
      } else if (item.dataType === "1") {
        if (length > 0) {
          if (!obj[key][length - 1].radar) {
            obj[key][length - 1].number += 1;
          } else {
            const aisData = { ais: '虚拟AIS', number: 1, time: item.currentTime };
            obj[key].push(aisData);
          }
        }
      }
    }
  }
  return obj;
}

// 复制到粘贴板
export function copyToClipboard(data) {
  const textToCopy = JSON.stringify(data, null, 2);  // 格式化为JSON字符串
  navigator.clipboard.writeText(textToCopy)
    .then(() => {
      console.log('数据已复制到剪贴板');
    })
    .catch((err) => {
      console.error('复制到剪贴板失败: ', err);
    });
}

// 根据雷达和xy计算经纬度
export const getLonLatByXY = (x, y, type) => {
  const leida = {
    bei: {
      lon: 119.45206246145788,
      lat: 29.17467466774048,
      angle: 18 + 7,
    },
    nan: {
      lon: 119.45208554818058,
      lat: 29.17450635050248,
      angle: 201 + 5.5,
    }
  }
  const now = leida[type]
  const { angle, distance } = calculateDistanceAndAngle(x, y);
  const m = calculateDestination(now.lat, now.lon, now.angle + angle, distance);
  return {
    latitude: m.lat,
    longitude: m.lon,
  }
}

// 随机颜色
export function getRandomColor() {
  const getHex = () => Math.floor(Math.random() * 256).toString(16).padStart(2, '0'); // 生成两位十六进制
  const red = getHex();     // 随机红色分量
  const green = getHex();   // 随机绿色分量
  const blue = getHex();    // 随机蓝色分量
  // const alpha = 'b3';       // 固定透明度值
  return `#${red}${green}${blue}`;
}

// 根据V计算速度
export function getSpeedByV(row) {
  return Math.abs(row.v / Math.cos(row.azimuth * Math.PI / 180)) * 3600 / 1852;
}